package com.decade.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.decade.entity.Stock;
import com.decade.mapper.StockMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gzk
 * @date 2021/49/11 15:49
 */
@Service
public class StockServiceImpl implements StockService{
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据商品id查询库存
     * @param goodsId
     * @return
     */
    @Override
    public Stock getStockByGoodsId(Long goodsId) {
        QueryWrapper<Stock> qw = new QueryWrapper<>();
        qw.eq("material_id", goodsId);
        return stockMapper.selectOne(qw);
    }

    @Override
    public boolean decrementProductStore(Long productId, Integer productQuantity) {
        String key = "dec_store_lock_" + productId;
        RLock lock = redissonClient.getLock(key);
        try {
            //加锁 操作很类似Java的ReentrantLock机制
            lock.lock();
            Stock stockInfo = this.getStockByGoodsId(productId);
            //如果库存为空
            if (stockInfo.getUsableStock() == 0) {
                return false;
            }
            //简单减库存操作 没有重新写其他接口了
            stockInfo.setUsableStock(stockInfo.getUsableStock() - 1);
            stockMapper.updateById(stockInfo);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            //解锁
            lock.unlock();
        }
        return true;
    }
}
